package com.fengxu.gamescript.ui

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.TextView
import androidx.core.app.ActivityCompat
import com.alibaba.fastjson.JSONObject
import com.fengxu.gamescript.R
import com.fengxu.gamescript.data.Conf
import com.fengxu.gamescript.data.GlobalData
import com.fengxu.gamescript.data.po.User
import com.fengxu.gamescript.provide.ProviderFactory
import com.fengxu.gamescript.service.SafeService
import com.fengxu.gamescript.ui.base.BaseActivity
import com.fengxu.gamescript.ui.main.MainActivity
import com.fengxu.gamescript.ui.reg.RegisterActivity
import com.fengxu.gamescript.util.CommonUtils
import com.fengxu.gamescript.util.PermissionUtils
import com.xuexiang.xui.XUI
import com.xuexiang.xui.widget.button.roundbutton.RoundButton
import com.xuexiang.xui.widget.edittext.materialedittext.MaterialEditText
import com.xuexiang.xui.widget.toast.XToast
import org.jetbrains.anko.*
import kotlin.system.exitProcess

class LaunchActivity : BaseActivity() {

    // 配置对象
    private lateinit var conf: Conf;

    // 提示控件
    private val tipView:TextView by lazy {
        findViewById(R.id.launch_tip)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_launch)
        // 设置主线程名为main
        Thread.currentThread().name = "main"
        // 开启安全服务
//        startService(Intent(this, SafeService::class.java))
        // 初始化配置文件
        Conf.initConf(this)
        conf = Conf.getConf()
        conf.isStartFlowWin = conf.isStartFlowWin && PermissionUtils.checkFloatPermission(this)
        // 检查权限
        if(checkPermission()){
           enterMain()
        }
   }

    /**
     * 进入主界面
     */
    private fun enterMain(){
        tipView.text = "环境监测成功"
        doAsync {
            Thread.sleep(1500)
            var user = User()
            user.remainTimes = 10000
            user.email = "123456789@qq.com"
            user.expire = 1800000000
            user.role = 2
            user.signIn = true
            user.updateTime = 1L
            GlobalData.user = user
            runOnUiThread {
                startActivity(Intent(this@LaunchActivity, MainActivity::class.java))
            }
        }
    }


    /**
     * 检查权限
     */
    private fun checkPermission() :Boolean{
        val permissions = arrayOf<String>(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
        // 当安卓版本大于等于11时
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
            // 不具有权限时
            if(!Environment.isExternalStorageManager()){
                CommonUtils.toastDialog(this,cancelable = false,content = "软件需要文件读写权限才能正常运行，请授权!",
                    onPositive = {
                        val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                        intent.setData(Uri.parse("package:$packageName"))
                        startActivityForResult(intent,101)
                    })
                return false
            }
        }
        // 当安卓版本大于等于6时
        else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !PermissionUtils.checkReadWritePermission(this)){
            ActivityCompat.requestPermissions(this, permissions, 1)
            return false
        }
        return true
    }

    /**
     * 权限申请回调
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if(!grantResults.all { it == PackageManager.PERMISSION_GRANTED }){
            CommonUtils.toastDialog(this, content = "您未赋予所需权限，程序无法运行!",
                    cancelable = false,
                    onPositive = { exitProcess(0) })
        } else {
            enterMain()
        }
    }

}